package top.continew.admin.generator.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.continew.admin.common.context.UserContextHolder;
import top.continew.admin.common.enums.TaskStatusEnums;
import top.continew.admin.generator.mapper.TaskListMapper;
import top.continew.admin.generator.mapper.TaskTransferMapper;
import top.continew.admin.generator.model.entity.TaskAssignmentDO;
import top.continew.admin.generator.model.entity.TaskListDO;
import top.continew.admin.generator.model.entity.TaskTransferDO;
import top.continew.admin.generator.model.req.TransferApplyReq;
import top.continew.admin.generator.model.req.TransferHandleReq;
import top.continew.admin.generator.model.resp.TransferChainResp;
import top.continew.admin.generator.service.TaskAssignmentService;
import top.continew.admin.generator.service.TaskTransferService;
import top.continew.admin.system.model.resp.user.UserDetailResp;
import top.continew.admin.system.service.UserService;
import top.continew.starter.core.exception.BusinessException;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务转派服务实现
 */
@Service
@RequiredArgsConstructor
public class TaskTransferServiceImpl extends ServiceImpl<TaskTransferMapper, TaskTransferDO> implements TaskTransferService {

    private final TaskListMapper taskListMapper;
    private final TaskAssignmentService taskAssignmentService;
    private final UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyTransfer(TransferApplyReq req) {
        Long currentUserId = UserContextHolder.getContext().getId();

        // 检查是否已有待处理的转派申请
        boolean hasPending = this.exists(new LambdaQueryWrapper<TaskTransferDO>()
                .eq(TaskTransferDO::getTaskId, req.getTaskId())
                .eq(TaskTransferDO::getTransferStatus, 1));
        if (hasPending) {
            throw new BusinessException("该任务已有待处理的转派申请");
        }

        // 创建转派记录
        TaskTransferDO transfer = new TaskTransferDO();
        transfer.setTaskId(req.getTaskId());
        transfer.setFromUserId(currentUserId);
        transfer.setToUserId(req.getToUserId());
        transfer.setTransferReason(req.getTransferReason());
        transfer.setTransferStatus(1); // 待处理
        transfer.setTransferTime(LocalDateTime.now());
        transfer.setAttachmentUrls(req.getAttachmentUrls());
        
        this.save(transfer);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleTransfer(TransferHandleReq req) {
        // 查询转派记录
        TaskTransferDO transfer = this.getById(req.getTransferId());
        if (transfer == null) {
            throw new BusinessException("转派记录不存在");
        }

        if (!transfer.getTransferStatus().equals(1)) {
            throw new BusinessException("转派申请已处理");
        }
        // 获取任务信息以获取batchId
        TaskListDO taskInfo = taskListMapper.selectById(transfer.getTaskId());
        String batchId = taskInfo != null ? taskInfo.getBatchId() : null;

        // 更新转派记录
        transfer.setTransferStatus(req.getHandleResult());
        transfer.setHandleTime(LocalDateTime.now());

        // 更新原任务分配状态
        TaskAssignmentDO assignmentDO = new TaskAssignmentDO();
        assignmentDO.setStatus(TaskStatusEnums.REASSIGNED.getValue());
        taskAssignmentService.update(assignmentDO, new LambdaQueryWrapper<TaskAssignmentDO>().eq(TaskAssignmentDO::getTaskId, transfer.getTaskId()));

        if (req.getHandleResult().equals(3)) { // 退回
            if (StrUtil.isBlank(req.getRejectReason())) {
                throw new BusinessException("退回时必须填写退回原因");
            }
            transfer.setRejectReason(req.getRejectReason());

            // 更新任务状态


        } else if (req.getHandleResult().equals(2)) { // 接受
            transfer.setToUserId(req.getReceiverId());
            if (req.getReceiverId() == null) {
                throw new BusinessException("接受时必须选择接收人");
            }
            
            UserDetailResp receiver = userService.get(req.getReceiverId());
            if (receiver == null) {
                throw new BusinessException("接收人不存在");
            }

            // 创建新的任务分配
            TaskAssignmentDO newAssignment = new TaskAssignmentDO();
            newAssignment.setTaskId(taskInfo.getId());
            newAssignment.setHandlerId(req.getReceiverId());
            newAssignment.setHandlerName(receiver.getNickname());
            newAssignment.setStatus(TaskStatusEnums.UN_DO.getValue());
            newAssignment.setBatchId(batchId);
            taskAssignmentService.save(newAssignment);
        }
        // 更新任务状态
        TaskListDO task = new TaskListDO();
        task.setId(taskInfo.getId());
        task.setTaskStatus(TaskStatusEnums.UN_DO.getValue());
        task.setUpdateTime(LocalDateTime.now());
        taskListMapper.updateById(task);

        this.updateById(transfer);
    }

    @Override
    public List<TransferChainResp> getTransferChain(Long taskId) {
        return baseMapper.selectTransferChain(taskId);
    }
}